﻿using System;
using System.Web;
using System.Web.Routing;
using SacNetUG.Models;

namespace SacNetUG.Constraints
{
    public class CmsContentConstraint : IRouteConstraint
    {
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            if(!MvcApplication.RoutesLoaded)
            {
                MvcApplication.RoutesLoaded = true;

                var db = new SacNetUGRepository();
                MvcApplication.CmsRoutes = db.GetCmsRoutes();
            }

            if (MvcApplication.CmsRoutes.Contains(String.Format("{0}.{1}", values["controller"], values["action"]).ToLower()))
            {
                //route to the Content/Detail View
                values.Add("controllerToView", values["controller"]);
                values.Add("actionToView", values["action"]);
                values["controller"] = "Content";
                values["action"] = "Detail";
            }

            //this constraint is used on the default route and must always return true
            return true;
        }
    }
}
